﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace BaseSyntax.ThreadTest
{
	public class RequestAsyncWaitIO : ITest
	{
		public async Task Test1()
		{
			string url = "https://www.google.com";

			try
			{
				Console.Write(url);

				WebRequest webRequest =
					WebRequest.Create(url);

				// 进程会堵塞，直到请求结束，在请求正常回来之前，.....不会打印
				WebResponse response =
					await webRequest.GetResponseAsync();

				Console.Write(".....");

				using (StreamReader reader = new StreamReader(response.GetResponseStream()))
				{
					string text =
						reader.ReadToEnd();
					Console.WriteLine(
						FormatBytes(text.Length));
				}
			}
			catch (WebException e)
			{
				Console.WriteLine(e);
			}
			catch (IOException e)
			{
				Console.WriteLine(e);
			}
			catch (NotSupportedException e)
			{
				Console.WriteLine(e);
			}
			finally
			{
				Console.WriteLine("finally");
			}
		}
		public string FormatBytes(long bytes)
		{
			string[] magnitudes =
				new string[] { "GB", "MB", "KB", "Bytes" };
			long max =
				(long)Math.Pow(1024, magnitudes.Length);

			return string.Format("{1:##.##} {0}",
				magnitudes.FirstOrDefault(
					magnitude =>
						bytes > (max /= 1024)) ?? "0 Bytes",
				(decimal)bytes / (decimal)max);
		}
		
		public void Test()
		{
			Task task = Test1();
			task.Wait();
		}
	}
}